<?php

/**
 * Demand actions.
 *
 * @package    ProdAssistant
 * @subpackage Demand
 * @author     Paweł Świtalla
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class DemandActions extends sfActions
{
  private $core;
  public function preExecute()
  {
    $this->core = PACore::getInstance();
  }
  
  public function executeSelectDeliverer(sfWebRequest $request)
  {
    $this->form = new SelectDelivererForm();
    if($this->form->hasRecords()) $this->showForm = false;
    else $this->showForm = true;
    
    if($request->isMethod('post'))
    {
      $this->delivererId = $request->getParameter('deliverer_id');
      if($request->isXmlHttpRequest())
      {
        $core = PACore::getInstance();
        $url = $core->generateAppUrl('Production', 'createDemand', null, array('deliverer' => $this->delivererId));
        $this->getResponse()->setContent('location@'.$url.'#');
        return sfView::NONE;
      }
    }
  }
  
  public function executeSelectCategory(sfWebRequest $request)
  {
    $this->form = new SelectCategoryForm();
    
    if($this->form->hasRecords()) $this->showForm = false;
    else $this->showForm = true;
    
    if($request->isMethod('post'))
    {
      $this->categoryId = $request->getParameter('category_id');
      if($request->isXmlHttpRequest())
      {
        $core = PACore::getInstance();
        $url = $core->generateAppUrl('Production', 'createDemand', null, array('category' => $this->categoryId));
        $this->getResponse()->setContent('location@'.$url.'#');
        return sfView::NONE;
      }
    }
  }
  
  public function executeSelectYawalXlsFile(sfWebRequest $request)
  {
    $this->form = new SelectYawalXlsFileForm();
    if($request->isMethod("post")){
      $this->form->bind(
        $request->getParameter("select_yawal_xls"),
        $request->getFiles("select_yawal_xls")
      );
      if($this->form->isValid()){
        $file = $this->form->getValue('file');
        $extension = $file->getOriginalExtension();
        if($extension == ".xls" || $extension == ".XLS"){
          $fileName = "yawal_xls_".time();
          $file->save(sfConfig::get("sf_upload_dir").DIRECTORY_SEPARATOR.$fileName.".xls");
          $yawalReader = new PAYawalExcelReader(sfConfig::get("sf_upload_dir").DIRECTORY_SEPARATOR.$fileName.".xls");
          $this->items = $yawalReader->getDataRows();
          $this->result = ProductionDemand::checkXlsDemand($yawalReader);
          $this->setTemplate("yawalXlsDemandPreview");
          $this->projectForm = new SelectProjectForm();
        }
      }
    }
  }
  
  public function executeCreateFromYawalXls(sfWebRequest $request)
  {
    $deliverer = Doctrine_Query::create()
            ->select('d.*')
            ->from('Deliverer d')
            ->where('d.name LIKE ?', 'Yawal%')
            ->execute()
            ->getFirst();
            
    $this->quantities = $request->getParameter('quantities');
    $this->includes = $request->getParameter('include');
    
    $items = array_intersect_key($this->quantities, $this->includes);
    
    $demand = new ProductionDemand();
    $demand->setProjectId($request->getParameter('project'));
    $demand->setUser($this->getUser()->getAttribute('userObject'));
    $demand->setDescription($request->getParameter('demandDescription'));
    $demand->setDeliverer($deliverer);
    $demand->save();
    $demand->saveDemandItems($items);
    
    $demand->setNumber("LM-".$demand->getProject()->getShortcut()."-".date("Y-m-d", strtotime($demand->getCreatedAt()))."-".$demand->getId());
    $demand->save();
    
    $this->redirect($this->core->generateAppUrl('Production', 'demandHomepage'));
    
  }
  
  public function executeDemandList(sfWebRequest $request)
  {
    if(!$request->hasParameter('itemId'))
    {
      $this->demands = Doctrine_Core::getTable('ProductionDemand')->findAll();
    }
    else
    {
      $this->demands = ProductionDemandTable::getAllWithItem($request->getParameter('itemId'));
      $this->setLayout(PACore::getLayoutsDir().'/clear');
    }
  }
  
  public function executeCreate(sfWebRequest $request)
  {
    $url = $this->core->generateAppUrl('Production', 'demandHomepage');
    if($request->hasParameter('category') || $request->hasParameter('deliverer') || $request->isMethod('post'))
    {
      $id = '';
      $category = '';
      $deliverer = '';
      $this->form = new ProductionDemandForm(null, array('items_list', 'items_list_values', 'project_id', 'description'), array('categoryId' => $request->getParameter('category'), 'delivererId' => $request->getParameter('deliverer')));
      $this->quantityUnit = '';
      if($request->hasParameter('category'))
      {
        $category = Doctrine_Core::getTable('Category')->find($request->getParameter('category'));
        $this->getUser()->setFlash("category_id", $request->getParameter('category'));
        $this->quantityUnit = $category->getQuantityUnit();
      }
      elseif($request->hasParameter('deliverer'))
      {
        $deliverer = Doctrine_Core::getTable('Deliverer')->find($request->getParameter('deliverer'));
        $this->getUser()->setFlash("deliverer_id", $request->getParameter('deliverer'));
      }
      if($request->isMethod('post')){
        $params = $request->getParameter('production_demand');
        $this->form->bind($params);
        if($this->form->isValid()){
          ksort($params['items_list_values']);
          $demand = $this->form->getObject();
          $demand->setUser($this->getUser()->getAttribute('userObject'));
          $demand = $this->form->save();

          // TODO: Fazy projektów w nazwie dokumentu
          $demand->setNumber("LM-".$demand->getProject()->getShortcut()."-".date("Y-m-d", strtotime($demand->getCreatedAt()))."-".$demand->getId());
          $demand->updateDemandItems($params['items_list_values']);
          if($this->getUser()->hasFlash("category_id")) $demand->setCategoryId($this->getUser()->getFlash("category_id"));
          else if($this->getUser()->hasFlash("deliverer_id")) $demand->setDelivererId($this->getUser()->getFlash("deliverer_id"));
          $demand->save();

          if($request->isXmlHttpRequest())
          {
            $this->getResponse()->setContent('location@'.$url."#");
            return sfView::NONE;
          }
          else $this->redirect($url);
        }
      }
      if($request->isXmlHttpRequest())
      {
        $errors = '';
        foreach($this->form->getFormFieldSchema() as $field){
          if($field->hasError()){
            $errors .= ucfirst($field->getName()).': '.$field->getError()."\n";
          }
        }
        $this->getResponse()->setContent('error@'.$errors."#");
        return sfView::NONE;
      }
    }
    else $this->redirect($this->core->generateAppUrl('Production', 'selectCategory'));
  }
  
  public function executeShow(sfWebRequest $request)
  {
    if(!$request->hasParameter('itemId'))
    {
      $this->demand = Doctrine_Core::getTable('ProductionDemand')->find($request->getParameter('id'));
      $demand = Doctrine_Query::create()
              ->select('p.id, di.value, i.name, c.quantityUnit')
              ->from('ProductionDemand p')
              ->leftJoin('p.DemandItems di')
              ->leftJoin('di.StoreItem i')
              ->leftJoin('i.Category c')
              ->where('p.id = ?', $request->getParameter('id'))
              ->execute()
              ->toArray();
    }
    else
    {
      $this->demand = ProductionDemandTable::getLastWithItem($request->getParameter('itemId'));
      $demand = array();
      if($this->demand instanceof ProductionDemand)
      {
        $demand = Doctrine_Query::create()
                ->select('p.id, di.value, i.name, c.quantityUnit')
                ->from('ProductionDemand p')
                ->leftJoin('p.DemandItems di')
                ->leftJoin('di.StoreItem i')
                ->leftJoin('i.Category c')
                ->where('p.id = ?', $this->demand->getId())
                ->execute()
                ->toArray();
      }
    }
      
    if(count($demand) > 0)
    {
      $this->items = array();
      foreach($demand[0]['DemandItems'] as $item)
      {
        $this->items[] = array('name' => $item['StoreItem']['name'], 'quantity' => $item['value'], 'quantityUnit' => $item['StoreItem']['Category']['quantityUnit'], 'annotation' => '');
      }
    }
        
    $this->setLayout(PACore::getLayoutsDir()."/document");
  }
  
  public function executeDelete(sfWebRequest $request)
  {
    $demand = Doctrine_Core::getTable('ProductionDemand')->find($request->getParameter('id'));
    if($demand instanceof ProductionDemand)
    {
      $demand->delete();
    }
    $this->redirect($request->getReferer());
  }
}
